package com.ciaojian.core.util;

import cn.hutool.core.util.StrUtil;
import com.ciaojian.core.constant.RedisConstant;
import com.ciaojian.core.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * 用户工具类
 *
 * @author Atlakyn
 */
public class UserUtil {
    private static final UserMapper USER_MAPPER = ApplicationContextHelper.getBean(UserMapper.class);

    /**
     * 从 Redis 拿用户的 openId
     */
    public static String getOpenId(Integer userId) {
        // 获取user openid
        String openid = RedisUtil.getKey(RedisConstant.USER_OPEN_ID + userId);
        if (StrUtil.isBlank(openid)) {
            // 在Redis中没找到则到数据库中找
            openid = USER_MAPPER.getOpenIdById(userId);
            // 也为空则直接返回null
            if (StrUtil.isBlank(openid)) {
                return null;
            }
            // 存入Redis
            RedisUtil.setKey(RedisConstant.USER_OPEN_ID + userId, openid);
        }

        return openid;
    }
}
